<?php
namespace Info\Controller;
use Info\Controller\CommonController;
use Common\Model\InfoContentModel;
use Think\Model;

class ShareController extends CommonController {

    public function info(){
        $ip = get_client_ip();
        $sid = I("sid");
        $shareModel = M('info_share');
        $this->isExisteIP($ip,$sid);
        $map['id'] = array("eq",$sid);
        $shareData = $shareModel->where($map)->find();
        if($shareData['times'] >= 10){
            $data['end_time'] = strtotime('+7 day');
            $data['id'] = $sid;
            $res = $shareModel->save($data);
            $infoModel = new InfoContentModel();
            $infoData['id'] = $shareData['info_id'];
            $infoData['type'] = 1;
            $infoData['status_time'] = date("Y-m-d H:i:s",$data['end_time']);
            $infoModel->save($infoData);
        }
        $infoDdata = $this->getInfoById($shareData['info_id']);
        //获取父级栏目id
        $cateogry = $this->getFatherCategory($infoDdata['cid']);
        //相关栏目
        $HotCategory = $this->getInfoCategory($infoDdata['cid'],$cateogry['father']['id']);
        //相关信息
        if(!empty($infoDdata['phone'])){
            $data['phoneTimes'] = $this->getInfosByPhone($infoDdata['phone']);
        }else{
            $data['phoneTimes'] = 0;
        }
        $idArr = array_column($HotCategory,'id');
        $hotInfo = $this->getInfoInId($idArr);
        $this->assign('times',$shareData['times'])
            ->assign('infoDdata',$infoDdata)
            ->assign('category',$HotCategory)
            ->assign("hotInfo",$hotInfo);
        $this->display(":share_info");

    }

    public function isExisteIP($ip,$sid){
        $shareIpModel = M("info_share_ip");
        $ipWhere['ip'] = array('eq',$ip);
        $ipWhere['sid'] = array('eq',$sid);
        $isExistsIp = $shareIpModel->where($ipWhere)->find();
        if(!$isExistsIp){
            $data = array(
                'sid'   => $sid,
                'ip'    => $ip
            );
            $shareIpModel->add($data);
            $sql = "update __PREFIX__info_share set times = times + 1 where id = {$sid};";
            $sql = str_replace('__PREFIX__',C('DB_PREFIX'),$sql);
            $model = new Model();
            $model->execute($sql);
        }
        return true;
    }

    public function getInfoById($id){
        if(!empty($id)){
            $info = new InfoContentModel();
            $data = $info->find($id);
            if(!empty($info)){

                return $data;
            }else{
                //信息已过期或删除
                $this->redirect('/info/info/error404',array('id'=>$id));
            }
        }
        $this->redirect("/info/index");
    }

}